#include <iostream>
#include <fstream>
#include <string>

class Person {
public:
    std::string name;
    int age;

    Person(const std::string& n, int a) : name(n), age(a) {}

    // 序列化函数：将对象的状态写入文件
    void Serialize(std::ofstream& ofs) const {
        ofs << name << std::endl;
        ofs << age << std::endl;
    }

    // 反序列化函数：从文件中读取数据并恢复对象的状态
    void Deserialize(std::ifstream& ifs) {
        std::getline(ifs, name);
        ifs >> age;
    }

    void Print() const {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    // 创建一个 Person 对象
    Person person("Alice", 30);

    // 序列化对象并保存到文件
    std::ofstream outputFile("person.txt");
    if (outputFile.is_open()) {
        person.Serialize(outputFile);
        outputFile.close();
        std::cout << "Object serialized and saved to file." << std::endl;
    } else {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    // 从文件中反序列化对象
    Person loadedPerson("", 0);  // 创建一个空对象
    std::ifstream inputFile("person.txt");
    if (inputFile.is_open()) {
        loadedPerson.Deserialize(inputFile);
        inputFile.close();
        std::cout << "Object deserialized from file." << std::endl;
    } else {
        std::cerr << "Failed to open file for reading." << std::endl;
        return 1;
    }

    // // 打印反序列化后的对象
    loadedPerson.Print();

    return 0;
}
